package com.zhentao.controller;

import com.zhentao.service.ChatMessageMigrationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 聊天数据迁移控制器
 * 用于执行聊天消息的数据迁移操作
 */
@RestController
@RequestMapping("/chat/migration")
public class ChatMigrationController {

    private static final Logger log = LoggerFactory.getLogger(ChatMigrationController.class);

    @Autowired
    private ChatMessageMigrationService migrationService;

    /**
     * 执行头像信息迁移
     */
    @PostMapping("/avatars")
    public ResponseEntity<Map<String, Object>> migrateAvatars() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("开始执行头像信息迁移...");
            
            // 获取迁移前的统计信息
            Map<String, Object> beforeStats = migrationService.getAvatarMigrationStats();
            log.info("迁移前统计: {}", beforeStats);
            
            // 执行迁移
            migrationService.migrateAvatarsForAllMessages();
            
            // 获取迁移后的统计信息
            Map<String, Object> afterStats = migrationService.getAvatarMigrationStats();
            log.info("迁移后统计: {}", afterStats);
            
            response.put("success", true);
            response.put("message", "头像信息迁移完成");
            response.put("beforeStats", beforeStats);
            response.put("afterStats", afterStats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("头像信息迁移失败", e);
            
            response.put("success", false);
            response.put("message", "头像信息迁移失败: " + e.getMessage());
            response.put("error", e.getClass().getSimpleName());
            
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取头像迁移统计信息
     */
    @GetMapping("/avatars/stats")
    public ResponseEntity<Map<String, Object>> getAvatarMigrationStats() {
        try {
            Map<String, Object> stats = migrationService.getAvatarMigrationStats();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取头像迁移统计信息失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计信息失败: " + e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 执行会话ID迁移（原有功能）
     */
    @PostMapping("/conversation-ids")
    public ResponseEntity<Map<String, Object>> migrateConversationIds() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("开始执行会话ID迁移...");
            
            // 获取迁移前的验证结果
            ChatMessageMigrationService.MigrationResult beforeResult = migrationService.validateMigration();
            log.info("迁移前验证结果: {}", beforeResult);
            
            // 执行迁移
            migrationService.migrateExistingMessages();
            
            // 获取迁移后的验证结果
            ChatMessageMigrationService.MigrationResult afterResult = migrationService.validateMigration();
            log.info("迁移后验证结果: {}", afterResult);
            
            response.put("success", true);
            response.put("message", "会话ID迁移完成");
            response.put("beforeResult", beforeResult);
            response.put("afterResult", afterResult);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("会话ID迁移失败", e);
            
            response.put("success", false);
            response.put("message", "会话ID迁移失败: " + e.getMessage());
            response.put("error", e.getClass().getSimpleName());
            
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取会话ID迁移验证结果
     */
    @GetMapping("/conversation-ids/validate")
    public ResponseEntity<Map<String, Object>> validateConversationIdMigration() {
        try {
            ChatMessageMigrationService.MigrationResult result = migrationService.validateMigration();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", result);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("验证会话ID迁移失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "验证失败: " + e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 执行完整迁移（会话ID + 头像信息）
     */
    @PostMapping("/full")
    public ResponseEntity<Map<String, Object>> fullMigration() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("开始执行完整数据迁移...");
            
            // 1. 执行会话ID迁移
            log.info("步骤1: 执行会话ID迁移");
            migrationService.migrateExistingMessages();
            
            // 2. 执行头像信息迁移
            log.info("步骤2: 执行头像信息迁移");
            migrationService.migrateAvatarsForAllMessages();
            
            // 3. 获取最终统计信息
            ChatMessageMigrationService.MigrationResult conversationResult = migrationService.validateMigration();
            Map<String, Object> avatarStats = migrationService.getAvatarMigrationStats();
            
            response.put("success", true);
            response.put("message", "完整数据迁移完成");
            response.put("conversationIdResult", conversationResult);
            response.put("avatarStats", avatarStats);
            
            log.info("完整数据迁移完成");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("完整数据迁移失败", e);
            
            response.put("success", false);
            response.put("message", "完整数据迁移失败: " + e.getMessage());
            response.put("error", e.getClass().getSimpleName());
            
            return ResponseEntity.status(500).body(response);
        }
    }
}
